/*
 * MIT License
 *
 * Copyright (c) 2025 Mark·虎
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

package com.hsxxherp.key.uia.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hsxxherp.key.uia.entity.SysAppParameterTemplate;
import com.hsxxherp.key.uia.entity.SysAppParameterTemplateVersion;
import com.hsxxherp.key.uia.mapper.SysAppParameterTemplateMapper;
import com.hsxxherp.key.uia.service.ISysAppParameterTemplateService;
import com.hsxxherp.key.uia.service.ISysAppParameterTemplateVersionService;
import com.hsxxherp.key.uia.service.ISysAppVersionTemplateRelationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service
public class SysAppParameterTemplateServiceImpl extends ServiceImpl<SysAppParameterTemplateMapper, SysAppParameterTemplate>
        implements ISysAppParameterTemplateService {

    private static final Logger logger = LoggerFactory.getLogger(SysAppParameterTemplateServiceImpl.class);

    @Autowired
    private ISysAppParameterTemplateVersionService sysAppParameterTemplateVersionService;

    @Autowired
    private ISysAppVersionTemplateRelationService sysAppVersionTemplateRelationService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysAppParameterTemplate createDefaultTemplate(String appId) {
        // 参数校验
        if (appId == null || appId.isEmpty()) {
            logger.error("创建默认参数模板时，应用 ID 为空");
            throw new IllegalArgumentException("应用 ID 不能为空");
        }

        SysAppParameterTemplate template = buildDefaultTemplate(appId);
        try {
            if (!saveTemplate(template)) {
                handleFailure("创建默认参数模板", template.getTemplateId());
                return null;
            }
            SysAppParameterTemplateVersion templateVersion = createTemplateVersion(template.getTemplateId());
            if (templateVersion == null) {
                handleFailure("创建参数模板默认版本", template.getTemplateId());
                return null;
            }
            if (!createRelation(templateVersion.getTemplateVersionId())) {
                handleFailure("保存版本与模板的关联关系", template.getTemplateId());
                return null;
            }
            logger.info("成功创建默认参数模板，模板 ID: {}", template.getTemplateId());
            return template;
        } catch (Exception e) {
            logger.error("创建默认参数模板时发生异常，应用 ID: {}", appId, e);
            throw new RuntimeException("创建默认参数模板时发生异常", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysAppParameterTemplate createCustomTemplate(SysAppParameterTemplate template) {
        // 参数校验
        if (template == null) {
            logger.error("创建自定义参数模板时，传入的模板对象为 null");
            throw new IllegalArgumentException("参数模板对象不能为空");
        }
        if (template.getAppId() == null || template.getAppId().isEmpty()) {
            logger.error("创建自定义参数模板时，应用 ID 为空");
            throw new IllegalArgumentException("应用 ID 不能为空");
        }

        try {
            if (!saveTemplate(template)) {
                handleFailure("创建自定义参数模板", template.getTemplateId());
                return null;
            }
            SysAppParameterTemplateVersion templateVersion = createTemplateVersion(template.getTemplateId());
            if (templateVersion == null) {
                handleFailure("创建参数模板默认版本", template.getTemplateId());
                return null;
            }
            if (!createRelation(templateVersion.getTemplateVersionId())) {
                handleFailure("保存版本与模板的关联关系", template.getTemplateId());
                return null;
            }
            logger.info("成功创建自定义参数模板，模板 ID: {}", template.getTemplateId());
            return template;
        } catch (Exception e) {
            logger.error("创建自定义参数模板时发生异常，模板信息: {}", template, e);
            throw new RuntimeException("创建自定义参数模板时发生异常", e);
        }
    }

    private SysAppParameterTemplate buildDefaultTemplate(String appId) {
        SysAppParameterTemplate template = new SysAppParameterTemplate();
        template.setAppId(appId);
        template.setTemplateName("默认配置模板");
        template.setTemplateDescription("这是应用创建时自动生成的默认配置模板");
        template.setSortOrder(1);
        return template;
    }

    private boolean saveTemplate(SysAppParameterTemplate template) {
        return super.save(template);
    }

    private SysAppParameterTemplateVersion createTemplateVersion(String templateId) {
        return sysAppParameterTemplateVersionService.createParameterTemplateVersion(
                buildDefaultTemplateVersion(templateId));
    }

    private SysAppParameterTemplateVersion buildDefaultTemplateVersion(String templateId) {
        SysAppParameterTemplateVersion templateVersion = new SysAppParameterTemplateVersion();
        templateVersion.setTemplateId(templateId);
        templateVersion.setVersionNumber("1.0.0");
        templateVersion.setVersionDescription("默认模板版本");
        return templateVersion;
    }

    private boolean createRelation(String templateVersionId) {
        return sysAppVersionTemplateRelationService.createRelation(templateVersionId, templateVersionId);
    }

    private void handleFailure(String operation, String templateId) {
        logger.error("{} 失败，模板 ID: {}", operation, templateId);
        throw new RuntimeException(operation + " 失败");
    }
}